import { Body, Controller, Post, Inject } from '@midwayjs/core';
import { ApiResponse, ApiTags } from '@midwayjs/swagger';
import { Context } from '@midwayjs/koa';
import {
  AnnouncementItemResDto,
  AnnouncementId,
  FlagResDto,
  AnnouncementEdit,
  AnnouncementCommon,
  Pagination,
} from '../model';
import { ServerResponse } from '../util/response';
import { AnnouncementService } from '../service/announcement.service';

@ApiTags(['社区公告'])
@Controller('/announcement')
export class AnnouncementController {
  @Inject()
  ctx: Context;

  @Inject()
  announcementService: AnnouncementService;

  @Post('/list', { summary: '社区公告列表' })
  @ApiResponse({
    status: 200,
    description: 'ok',
    type: AnnouncementItemResDto,
  })
  async list(@Body() req: Pagination) {
    const params: Pagination = {
      pageNo: 1,
      pageSize: 10,
      ...req,
    };
    const res = await this.announcementService.getList(params);
    return ServerResponse.JSON_TPL({
      list: res.rows,
      pagination: {
        ...params,
        total: res.count,
      },
    });
  }

  @Post('/add', { summary: '添加公告' })
  @ApiResponse({
    status: 200,
    description: 'ok',
    type: FlagResDto,
  })
  async add(@Body() req: AnnouncementCommon) {
    const res = await this.announcementService.addItem(req);
    return ServerResponse.JSON_TPL({
      flag: Object.keys(res).length > 0,
    });
  }

  @Post('/edit', { summary: '修改公告' })
  @ApiResponse({
    status: 200,
    description: 'ok',
    type: FlagResDto,
  })
  async edit(@Body() req: AnnouncementEdit) {
    const res = await this.announcementService.editItem(req);
    if (Boolean(res[0])) {
      return ServerResponse.JSON_TPL({
        flag: Boolean(res[0]),
      });
    }
    return ServerResponse.JSON_TPL(
      {
        flag: Boolean(res[0]),
      },
      Boolean(res[0]),
      '不存在该公告'
    );
  }

  @Post('/del', { summary: '删除公告' })
  @ApiResponse({
    status: 200,
    description: 'ok',
    type: FlagResDto,
  })
  async del(@Body() req: AnnouncementId) {
    const res = await this.announcementService.delItem(req);
    if (Boolean(res)) {
      return ServerResponse.JSON_TPL({
        flag: Boolean(res),
      });
    }
    return ServerResponse.JSON_TPL(
      {
        flag: Boolean(res),
      },
      Boolean(res),
      '不存在该公告'
    );
  }

  @Post('/byId', { summary: '公告详情' })
  @ApiResponse({
    status: 200,
    description: 'ok',
    type: FlagResDto,
  })
  async byId(@Body() req: AnnouncementId) {
    const res = await this.announcementService.byIdItem(req);
    return ServerResponse.JSON_TPL(res);
  }
}
